<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import dayjs from 'dayjs';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Space,
  message,
  Tag,
} from 'ant-design-vue';
import type { TableColumnsType, TablePaginationConfig } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue/es/form';

import {
  createTaskServiceTypeApi,
  deleteTaskServiceTypeApi,
  getTaskServiceTypesApi,
  updateTaskServiceTypeApi,
  type TaskServiceTypeApi,
} from '#/api/core';

const loading = ref(false);
const saving = ref(false);
const records = ref<TaskServiceTypeApi.TaskServiceTypeRecord[]>([]);
const formRef = ref<FormInstance>();
const isModalVisible = ref(false);
const isEditing = ref(false);
const currentId = ref<number | null>(null);
const searchKeyword = ref('');

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const formatDateTime = (value?: string) => {
  if (!value) return '';
  const parsed = dayjs(value);
  return parsed.isValid() ? parsed.format('YYYY-MM-DD HH:mm:ss') : value;
};

const formState = reactive({
  name: '',
});

const columns: TableColumnsType<TaskServiceTypeApi.TaskServiceTypeRecord> = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '服务类型名称', dataIndex: 'name', key: 'name', ellipsis: true },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 200,
  },
  {
    title: '更新时间',
    dataIndex: 'updated_at',
    key: 'updated_at',
    width: 200,
  },
  {
    title: '操作',
    key: 'actions',
    width: 160,
  },
];

const resetForm = () => {
  formState.name = '';
  formRef.value?.clearValidate();
};

const openCreateModal = () => {
  isEditing.value = false;
  currentId.value = null;
  resetForm();
  isModalVisible.value = true;
};

const openEditModal = (record: TaskServiceTypeApi.TaskServiceTypeRecord) => {
  isEditing.value = true;
  currentId.value = record.id;
  formState.name = record.name;
  formRef.value?.clearValidate();
  isModalVisible.value = true;
};

const closeModal = () => {
  isModalVisible.value = false;
  saving.value = false;
  isEditing.value = false;
  currentId.value = null;
  resetForm();
};

const fetchList = async (page = pagination.current, perPage = pagination.pageSize) => {
  loading.value = true;
  try {
    const response = await getTaskServiceTypesApi({
      page,
      per_page: perPage,
      keyword: searchKeyword.value || undefined,
    });
    records.value = response.items;
    pagination.current = response.pagination.current_page;
    pagination.pageSize = response.pagination.per_page;
    pagination.total = response.pagination.total;
  } catch (error) {
    console.error('获取服务类型列表失败', error);
    message.error('获取服务类型列表失败');
  } finally {
    loading.value = false;
  }
};

const handleTableChange = (pager: TablePaginationConfig) => {
  const current = pager.current ?? pagination.current;
  const pageSize = pager.pageSize ?? pagination.pageSize;
  fetchList(current, pageSize);
};

const handleSearch = (value?: string) => {
  if (value !== undefined) {
    searchKeyword.value = value;
  }
  pagination.current = 1;
  fetchList(1, pagination.pageSize);
};

const submitForm = async () => {
  if (!formRef.value) return;
  try {
    const values = await formRef.value.validate();
    saving.value = true;
    if (isEditing.value && currentId.value) {
      await updateTaskServiceTypeApi(currentId.value, values);
      message.success('服务类型更新成功');
    } else {
      await createTaskServiceTypeApi(values);
      message.success('服务类型创建成功');
    }
    closeModal();
    await fetchList(isEditing.value ? pagination.current : 1, pagination.pageSize);
  } catch (error: any) {
    if (error?.errorFields) {
      return;
    }
    console.error('保存服务类型失败', error);
    message.error('保存服务类型失败');
  } finally {
    saving.value = false;
  }
};

const confirmDelete = (record: TaskServiceTypeApi.TaskServiceTypeRecord) => {
  Modal.confirm({
    title: '确认删除该服务类型？',
    content: '删除后将无法恢复，请确认该服务类型未被任务使用。',
    okText: '删除',
    okButtonProps: { danger: true },
    cancelText: '取消',
    async onOk() {
      try {
        await deleteTaskServiceTypeApi(record.id);
        message.success('服务类型已删除');
        const nextPage =
          records.value.length === 1 && pagination.current > 1
            ? pagination.current - 1
            : pagination.current;
        await fetchList(nextPage, pagination.pageSize);
      } catch (error) {
        console.error('删除服务类型失败', error);
        message.error('删除服务类型失败');
        throw error;
      }
    },
  });
};

onMounted(() => {
  fetchList();
});
</script>

<template>
  <div class="p-5">
    <Card title="任务服务类型管理" :body-style="{ paddingTop: '0.75rem' }">
      <template #extra>
        <Space>
          <Input.Search
            v-model:value="searchKeyword"
            placeholder="搜索服务类型"
            allow-clear
            style="width: 220px"
            @search="handleSearch"
          />
          <Button type="primary" @click="openCreateModal">新增服务类型</Button>
        </Space>
      </template>

      <Table
        :loading="loading"
        :data-source="records"
        :columns="columns"
        row-key="id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showTotal: (total) => `共 ${total} 条`,
        }"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <Tag color="blue">{{ record.name }}</Tag>
          </template>
          <template v-else-if="column.key === 'created_at'">
            {{ formatDateTime(record.created_at) }}
          </template>
          <template v-else-if="column.key === 'updated_at'">
            {{ formatDateTime(record.updated_at) }}
          </template>
          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button type="link" @click="openEditModal(record)">编辑</Button>
              <Button type="link" danger @click="confirmDelete(record)">删除</Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <Modal
      v-model:open="isModalVisible"
      :title="isEditing ? '编辑服务类型' : '新增服务类型'"
      :confirm-loading="saving"
      @ok="submitForm"
      @cancel="closeModal"
      destroy-on-close
    >
      <Form ref="formRef" :model="formState" layout="vertical">
        <Form.Item
          label="服务类型名称"
          name="name"
          :rules="[{ required: true, message: '请输入服务类型名称' }]"
        >
          <Input v-model:value="formState.name" placeholder="请输入服务类型名称" :maxlength="100" />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>
